package com.t2t.top.ha;

import org.apache.zookeeper.ZooKeeper;
import redis.clients.jedis.Jedis;

public class RedisThread extends Thread {
	private String masterIP;
	private String slaveIP;
	private String path;
	private ZooKeeper zk;
	private String filename;

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public String getMasterIP() {
		return masterIP;
	}

	public void setMasterIP(String masterIP) {
		this.masterIP = masterIP;
	}

	public String getSlaveIP() {
		return slaveIP;
	}

	public void setSlaveIP(String slaveIP) {
		this.slaveIP = slaveIP;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public ZooKeeper getZk() {
		return zk;
	}

	public void setZk(ZooKeeper zk) {
		this.zk = zk;
	}

	public void run(){
		Jedis masterjedis = null;
		Jedis slavejedis = new Jedis(slaveIP, 6379);
		Runtime runtime = Runtime.getRuntime();
		try{
			while(true){
				String currdata  = null;
				try{
					masterjedis  = new Jedis(masterIP, 6379);
					currdata = masterjedis.ping();
				}catch(Exception e){
				}
				String data = new String(zk.getData("/zk", false, null),"utf-8");

				if(!"PONG".equals(currdata) && data.equals("master")){
					System.out.println("主服务器宕机了，启动从服务器"+slaveIP);
					slavejedis.slaveofNoOne();
					zk.setData("/zk", "slave".getBytes(), -1);
					if(path.equals("/zk/master")){
						zk.setData(path,( masterIP+":"+"wrong").getBytes(), -1);
					}
					String[] execMaster =  {"/bin/sh", "-c", filename+" destroy 169.254.19.9 " + masterIP};
					runtime.exec(execMaster,null,null);
					String[] execSlave = {"/bin/sh", "-c", filename+"  create 169.254.19.9 " + slaveIP};
					runtime.exec(execSlave, null, null);
				}

				if("PONG".equals(currdata) && data.equals("slave")){
					System.out.println("主服务器启动了，正在从从服务器同步数据。。。");
					masterjedis.slaveof(slaveIP, 6379);
					Thread.sleep(10000);
					System.out.println("主服务器同步数据完毕，恢复主从身份");
					masterjedis.slaveofNoOne();
					slavejedis.slaveof(masterIP, 6379);
					zk.setData("/zk", "master".getBytes(), -1);
					if(path.equals("/zk/master")){
						zk.setData(path,masterIP.getBytes(), -1);
					}
					String[] execMaster =  {"/bin/sh", "-c",filename+" create 169.254.19.9 "+masterIP};
					runtime.exec(execMaster,null,null);
					String[] execSlave = {"/bin/sh", "-c",filename+"  destroy 169.254.19.9 "+slaveIP};
					runtime.exec(execSlave,null,null);
				}
				Thread.sleep(3000);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}
